package tech.aistar.prj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import sun.rmi.server.InactiveGroupException;
import tech.aistar.prj.entity.Pet;
import tech.aistar.prj.entity.PetType;
import tech.aistar.prj.entity.Result;
import tech.aistar.prj.service.IPetService;
import tech.aistar.prj.service.IPetTypeService;
import tech.aistar.prj.service.impl.PetServiceImpl;
import tech.aistar.prj.service.impl.PetTypeServiceImpl;
import tech.aistar.prj.util.StringToDate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * 本类功能:
 *
 * @author cxylk
 * @date 2020/9/18 18:22
 */
@WebServlet(urlPatterns = "/pet/*")
public class PetHandlerAction extends HttpServlet {
    IPetService petService=new PetServiceImpl();
    private IPetTypeService petTypeService=new PetTypeServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo=req.getPathInfo();

        switch (pathInfo){
            case "/del":
                String sid=req.getParameter("sids");
                String[] sids=sid.split(":");
                if(null!=sids&&sids.length>0){
                    for(String id:sids){
                        petService.delById(Integer.valueOf(id));
                    }
                }
                //此处用重定向，用转发的话会删两次
                //req.getRequestDispatcher("/pet/indexData").forward(req,resp);
                resp.sendRedirect("/lk/pet/indexData");
                break;
            case "/indexData":
                //        List<Pet> petList=petService.findAll();

                //必须要判断，因为long是包装类型，为空的话会包空指针异常
                //1.如果第一次进来，因为没有选中，所有typeId是null
                //2.如果下拉框有可能选择-1(即默认设置的-1)
                String typeId=req.getParameter("type_id");

                //放入service中进行逻辑业务判断
//        //为空就让它等于-1，因为-1就是默认的值
//        typedId=typeId==null?"-1":typeId;
//        //String转换成long
//        Long tid=Long.valueOf(typeId);

                //3.接收搜索框
                String name=req.getParameter("name");

                String pageNow=req.getParameter("pageNow");
                pageNow=pageNow==null?"1":pageNow;

                String pageSize=req.getParameter("pageSize");
                if(pageSize==null||"-1".equals(pageSize)){
                    pageSize="2";
                }

                PageInfo<Pet> petPageInfo=petService.findByPage(typeId,name,Integer.valueOf(pageNow),Integer.valueOf(pageSize));


                List<PetType> petTypes=petTypeService.getAll();

                req.setAttribute("page",petPageInfo);
                req.setAttribute("types",petTypes);

                //为了进行下拉框的一个数据回显的功能，刚刚传过来的typeId继续回显到页面上
                req.setAttribute("typeId",typeId==null?"-1":typeId);
                req.setAttribute("name",name==null?"":name);

                //req.getRequestDispatcher("/pets/content.jsp").forward(req,resp);
                req.getRequestDispatcher("/pets/index.jsp").forward(req,resp);
                break;
            case "/del_one":
                String id=req.getParameter("id");
                petService.delById(Integer.valueOf(id));

                //为了模拟网络延迟
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                resp.sendRedirect("/prj/pet/indexData");
                break;
            case "/del_ajax":
                resp.setContentType("text/json;charset=utf-8");
                PrintWriter out=resp.getWriter();
                String ids=req.getParameter("id");
                int count=petService.delById(Integer.valueOf(ids));
//                int count=0;
                Result result;
                if(count==0){//删除失败
                    result=new Result("500","删除失败");
                }else{
                    result=new Result("200","删除成功");
                }
                String str= JSONArray.toJSONString(result);
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                out.print(str);//将json字符串返回给页面...
                break;
            case "/add":
                System.out.println("/add");
                String imgUrl=req.getParameter("imgUrl");
                String petName=req.getParameter("name");
//                System.out.println(petName);
                String age=req.getParameter("age");
                String birthday=req.getParameter("birthday");
                String petTypeId=req.getParameter("petTypeId");
                try {
                    Pet pet = new Pet(petName,Integer.valueOf(age),
                            StringToDate.parse(birthday,"yyyy-MM-dd"),imgUrl,Integer.valueOf(petTypeId));
                    petService.save(pet);
                    resp.sendRedirect("/prj/pet/indexData");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case "/findById":
                List<PetType> petTypes2=petTypeService.getAll();
                req.setAttribute("types",petTypes2);
                String pid=req.getParameter("id");
                //System.out.println(pid);
                Pet pet=petService.findById(Integer.valueOf(pid));
                req.setAttribute("pet",pet);
                req.getRequestDispatcher("/pets/update.jsp").forward(req,resp);
                break;
            case "/ajax_findById":
                //一定要设置为json，坑
                resp.setContentType("text/json;charset=utf-8");
                String pid2=req.getParameter("id");
                //System.out.println(pid2);
                Pet ajaxPet=petService.findById(Integer.valueOf(pid2));
                //System.out.println(ajaxPet);
                String str2=JSONArray.toJSONString(ajaxPet);
                PrintWriter out2=resp.getWriter();
                out2.print(str2);
                break;
            case "/update":
                String pet_id=req.getParameter("id");
                String imgUrl2=req.getParameter("imgUrl");
                String petName2=req.getParameter("name");
                String age2=req.getParameter("age");
                String birthday2=req.getParameter("birthday");
                //System.out.println(birthday2);
                String petTypeId2=req.getParameter("petTypeSelect");
                try {
                    Pet pet2=new Pet(Integer.valueOf(pet_id),petName2,Integer.valueOf(age2),StringToDate.parse(birthday2,"yyyy-MM-dd"),
                            imgUrl2,Integer.valueOf(petTypeId2));
                    petService.update(pet2);
                    resp.sendRedirect("/prj/pet/indexData");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case "/ajax_update":
                String ajaxId=req.getParameter("id");
                String ajaxImgUrl=req.getParameter("imgUrl");
                String ajaxName=req.getParameter("name");
                String ajaxAge=req.getParameter("age");
                String ajaxBirthday=req.getParameter("birthday");
                //System.out.println(ajaxBirthday);
                String ajaxPetTypeId=req.getParameter("petTypeId");
                try {
                    Pet ajaxPets=new Pet(Integer.valueOf(ajaxId),ajaxName,Integer.valueOf(ajaxAge),
                            StringToDate.parse(ajaxBirthday,"yyyy-MM-dd"),ajaxImgUrl,Integer.valueOf(ajaxPetTypeId));
                    //System.out.println(ajaxPets);
                    petService.update(ajaxPets);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
